//
//  MBSpaceMyCollectionShowViewController.m
//  MiBaoTu
//
//  Created by admin on 16/9/21.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBSpaceMusicClassViewController.h"
#import "MBSpaceAddMusicViewController.h"
#import "MBSongDetailController.h"
#import "MBDetailViewController.h"
#import "MBSpaceAlbumViewController.h"
#import "MBLoginController.h"
#import "MBSpaceSetUpNewDetailViewController.h"
#import "MBSpaceChangeAlbumNameViewController.h"

#import "MBSpaceCollectionMusicCell.h"
#import "MBSpaceCollectionCompileView.h"
#import "SharePLayerView.h"

#import "MBSongDetailForIpadController.h"

@interface MBSpaceMusicClassViewController ()<UITableViewDataSource,UITableViewDelegate,MBSpaceCollectionCompileViewDelegate,MBSpaceCollectionMusicCellDelegate,SharePLayerViewDelegate,UITextFieldDelegate> {

    UITableView                             *_tableView;
    MBSpaceCollectionCompileView            *_compileView;
    UIView                                  *_topView;
    UIView                                  *bgNoView;         //无数据时显示
    UITextField                             *_textField;
    UILabel                                 *_showLb;
    
    NSMutableArray                          *_selectMusicArr;//保存选中的歌曲
    CLShareManager *shareView;
    NSMutableDictionary                     *_selectCurrentMusicDic;    //选中歌曲
    MusicPLayType                           musicPlayType;              //类型
    NSMutableArray                          *_fileIDArr;                //已下载的歌曲类型
    NSMutableArray                          *_musicArr;
}

@property (nonatomic,assign)BOOL isCompiling;//是否批量编译
@property (nonatomic,assign)BOOL isAllSelcting;//是否全选

@end

@implementation MBSpaceMusicClassViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self onLoadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isCompiling = NO;
    self.isAllSelcting = NO;
    _selectMusicArr = [[NSMutableArray alloc]init];
    _selectCurrentMusicDic = [[NSMutableDictionary alloc]init];
    _fileIDArr = [[NSMutableArray alloc]init];
    _musicArr = [[NSMutableArray alloc]init];
    // Do any additional setup after loading the view.
    [self setNavBar];
    [self onCreateUI];
    [self onCreateUIForNoData];
}

#pragma mark - Actions
#pragma mark - UI
- (void)setNavBar
{
    if (self.type == MusicClassType_ErGe) {
        [self setTitleView:@"儿歌"];
        musicPlayType = MusicPLayType_ErGe;
    }
    else if (self.type == MusicClassType_GuoXue) {
        [self setTitleView:@"国学"];
        musicPlayType = MusicPLayType_GuoXue;
    }
    else if (self.type == MusicClassType_GuShi) {
        [self setTitleView:@"故事"];
        musicPlayType = MusicPLayType_GuShi;
    }
    else if (self.type == MusicClassType_YingWen) {
        [self setTitleView:@"英文"];
        musicPlayType = MusicPLayType_English;
    }
    else if (self.type == MusicClassType_QinZiXiu) {
        [self setTitleView:@"亲子秀"];
        musicPlayType = MusicPLayType_QinZiXiu;
    }
    else if (self.type == MusicClassType_Custom) {
        [self setTitleView:self.albumName];
        musicPlayType = MusicPLayType_AlbumList;
    }
    [self setBackItem];
    
    [self onSetRightNavBar:NO];
}

- (void)onSetRightNavBar:(BOOL)isNoData
{
    if (isNoData == YES) {
        //没数据 显示更多
        
        UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
        bt.frame = CGRectMake(0, 0, 60, 30);
        [bt setTitle:@"更多" forState:UIControlStateNormal];
        [bt setTitle:@"更多" forState:UIControlStateHighlighted];
        [bt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [bt setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        bt.titleLabel.font = [UIFont systemFontOfSize:13.f];
        [bt setTitleEdgeInsets:UIEdgeInsetsMake(0, 30, 0, 0)];
        [bt addTarget:self action:@selector(onSelectItemForMore) forControlEvents:UIControlEventTouchUpInside];
        [self setRightBarItems:bt];
    } else {
        [self setRightPlayerItem];
    }
}

- (void)onCreateUI
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.backgroundView = nil;
    _tableView.hidden = YES;
    [self.view addSubview:_tableView];
    _tableView.tableHeaderView = [self setTableHeaderViewWithIndex:3];

    //批量弹出框
    _compileView = [[MBSpaceCollectionCompileView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 100*PERCEN)];
    _compileView.delegate = self;
    _compileView.orientation = self.orientation;
    _compileView.hidden = YES;
    [self.view addSubview:_compileView];
    
    shareView = [[CLShareManager alloc] init];
}

- (void)onUpdateUIForView:(UIDeviceOrientation)orientation
{
    _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.view.height);
    _tableView.tableHeaderView = [self setTableHeaderViewWithIndex:3];
    _compileView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 100*PERCEN);
    _compileView.orientation = self.orientation;
    
    NSArray *arr = [[NSUserDefaults standardUserDefaults]objectForKey:@"SELECT_MUSIC_FEN_ALL"];
    if ([arr isKindOfClass:[NSArray class]]) {
        if (arr.count > 0) {
            //弹出批量框
            _tableView.height = self.view.height-_compileView.height;
            _compileView.top = _tableView.bottom;
            _compileView.hidden = NO;
        } else {
            //隐藏
            _tableView.height = self.view.height;
            _compileView.top = _tableView.bottom;
            _compileView.hidden = YES;
            self.isAllSelcting = NO; //不全选
            [_selectMusicArr removeAllObjects]; //删除所有选中的歌曲
        }
    }
    
    [_tableView reloadData];
}

//增加的3个头部按钮 播放、批量、更多
- (UIView *)setTableHeaderViewWithIndex:(NSInteger)index
{
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 120*PERCEN)];
    bgView.backgroundColor = [UIColor clearColor];
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, bgView.width, 100*PERCEN)];
    contentView.backgroundColor = [UIColor whiteColor];
    [bgView addSubview:contentView];
    
    float itemWidth = 20*PERCEN;
    float btWidth = 1.*(bgView.width-(index+1)*itemWidth)/index;
    if (ISIPAD) {
        itemWidth = 44*PERCEN;
        btWidth = 360*PERCEN;
    }
    for (int i=0; i<index; i++) {
        UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
        bt.frame = CGRectMake(itemWidth+(btWidth+itemWidth)*i, 18*PERCEN, btWidth, 64*PERCEN);
        if (ISIPAD) {
            bt.left = 440*PERCEN+(btWidth+itemWidth)*i;
        }
        bt.backgroundColor = [UIColor whiteColor];
        [bt setTitleColor:UIColorFromHex(0x333333) forState:UIControlStateNormal];
        bt.layer.cornerRadius = 6.f;
        bt.layer.masksToBounds = YES;
        bt.layer.borderColor = UIColorFromHex(0x999999).CGColor;
        bt.layer.borderWidth = 1;
        bt.tag = 1000+i;
        bt.titleLabel.font = [UIFont systemFontOfSize:13.];
        [bt addTarget:self action:@selector(onTapForMusicAction:) forControlEvents:UIControlEventTouchUpInside];
        [contentView addSubview:bt];
        
        if (i == 0) {
            [bt setTitle:@"播放全部" forState:UIControlStateNormal];
        }
        else if (i == 1) {
            [bt setTitle:@"批量操作" forState:UIControlStateNormal];
        }
        else if (i == 2) {
            [bt setTitle:@"更多" forState:UIControlStateNormal];
        }
    }
    
    return bgView;
}

- (void)back
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - 无音频UI
- (void)onCreateUIForNoData
{
//    _topView = [self setTableHeaderViewWithIndex:3];
//    _topView.top = NAV_HEIGHT;
//    _topView.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:_topView];
    
    //content
    bgNoView = [[UIView alloc]initWithFrame:CGRectMake(0, (WIDTH_5S ? (SCREEN_HEIGHT+NAV_HEIGHT-200)/2. : NAV_HEIGHT+490*PERCEN), SCREEN_WIDTH, 200)];
    if (!ISIPAD) {
        bgNoView.centery = self.view.centery;
    }
    bgNoView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bgNoView];
    
    UILabel * _nickNameLb = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, bgNoView.width, 20)];
    _nickNameLb.backgroundColor = [UIColor clearColor];
    _nickNameLb.textAlignment = NSTextAlignmentCenter;
    _nickNameLb.textColor = UIColorFromHex(0x333333);
    _nickNameLb.font = [UIFont systemFontOfSize:14.f];
    _nickNameLb.text = @"这个分类里面没有歌曲";
    [bgNoView addSubview:_nickNameLb];
    
    UILabel *_userDetailLb = [[UILabel alloc]initWithFrame:CGRectMake(_nickNameLb.left, _nickNameLb.bottom+20*PERCEN, _nickNameLb.width, 20)];
    _userDetailLb.backgroundColor = [UIColor clearColor];
    _userDetailLb.textAlignment = NSTextAlignmentCenter;
    _userDetailLb.textColor = UIColorFromHex(0x999999);
    _userDetailLb.font = [UIFont systemFontOfSize:13.f];
    _userDetailLb.text = @"你可以挑一些歌曲添加到这里";
    [bgNoView addSubview:_userDetailLb];
    
    UIButton *_loginBt = [UIButton buttonWithType:UIButtonTypeCustom];
    _loginBt.frame = CGRectMake((bgNoView.width-(ISIPAD?700*PERCEN:360*PERCEN))/2., _userDetailLb.bottom+80*PERCEN, (ISIPAD?700*PERCEN:360*PERCEN), (ISIPAD?100*PERCEN:80*PERCEN));
    _loginBt.layer.cornerRadius = 5.f;
    _loginBt.layer.masksToBounds = YES;
    _loginBt.layer.borderWidth = 1.f;
    _loginBt.layer.borderColor = TINK_BG_COLOR.CGColor;
    _loginBt.backgroundColor = TINK_BG_COLOR;
    [_loginBt setTitle:@"添加歌曲" forState:UIControlStateNormal];
    [_loginBt setTitle:@"添加歌曲" forState:UIControlStateHighlighted];
    [_loginBt setTitleColor:UIColorFromHex(0xffffff) forState:UIControlStateNormal];
    [_loginBt setTitleColor:UIColorFromHex(0xffffff) forState:UIControlStateHighlighted];
    _loginBt.titleLabel.font = [UIFont systemFontOfSize:14.f];
    [_loginBt addTarget:self action:@selector(onAddMusicAction) forControlEvents:UIControlEventTouchUpInside];
    [bgNoView addSubview:_loginBt];
}

// 按钮-添加歌曲
- (void)onAddMusicAction
{
    MBSpaceAddMusicViewController *addMusic = [[MBSpaceAddMusicViewController alloc]init];
    addMusic.type = MBSpaceAddMusicType_SetAlbum;
    addMusic.dataDic = _dataDic;
    [self.navigationController pushViewController:addMusic animated:YES];
}

#pragma mark - 数据加载
- (void)onLoadData
{
    NSArray *downedMusicArr = [UserManager standerDefult].downedMusicArr;
    [_fileIDArr removeAllObjects];
    NSMutableArray *arr1 = [[NSMutableArray alloc]init];
    NSMutableArray *arr2 = [[NSMutableArray alloc]init];
    for (int i=0; i<downedMusicArr.count; i++) {
        NSDictionary *dic = [downedMusicArr objectAtIndex:i];
        NSString *fileID = [dic objectForKey:@"fileID"];
        [arr1 addObject:fileID];
    }
    NSArray *downedQZXMusicArr = [[FMManageObject standerDefault]onSelectLocalParentChildShowCount];
    for (int i=0; i<downedQZXMusicArr.count; i++) {
        NSDictionary *dic = [downedQZXMusicArr objectAtIndex:i];
        NSString *fileID = [dic objectForKey:@"musicId"];
        if (![arr2 containsObject:fileID]) {
            [arr2 addObject:fileID];
        }
    }
    [_fileIDArr addObject:arr1];
    [_fileIDArr addObject:arr2];
    
    UserModel *model = [UserManager standerDefult].userModel;
    if (model) {
        [MBProgressHUD showHUDAddedTo:_tableView animated:YES];
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:SPACE_GETAUDIOLISTALBUM_URL_PATH,model.UserID,[_dataDic objectForKey:@"CateID"]] view:nil success:^(NSDictionary * json) {
            [MBProgressHUD hideHUDForView:_tableView animated:YES];
            if ([json[@"ret_code"] integerValue]==0) {
                NSArray *arr = json[@"data"];
                if ([arr isKindOfClass:[NSArray class]]) {
                    if (arr.count  > 0) {
                        
                        _tableView.hidden = NO;
                        bgNoView.hidden = YES;
                        _showLb.hidden = YES;
//                        _topView.hidden = bgNoView.isHidden;
                        [self onSetRightNavBar:_tableView.isHidden];
                        [_musicArr removeAllObjects];
                        [_musicArr addObjectsFromArray:arr];
                        
                        [_tableView reloadData];
                    } else {

                        _tableView.hidden = YES;
                        bgNoView.hidden = NO;
//                        _topView.hidden = bgNoView.isHidden;
                        [self onSetRightNavBar:_tableView.isHidden];
                        _showLb.hidden = NO;
                    }
                }
                
            } else {
                
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:_tableView animated:YES];
        }];
    } else {
        MBLoginController *registerLastVC = [[MBLoginController alloc] init];
        registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
        [self.navigationController pushViewController:registerLastVC animated:YES];
    }
    
}

#pragma mark - 跳转播放器
- (void)onSelectItemForWork
{
    [self onPlayMusic];
}

#pragma mark - 播放全部、批量、更多
- (void)onTapForMusicAction:(UIButton *)bt
{
    switch (bt.tag-1000) {
        case 0:
        {
            //播放全部
            if (_musicArr.count > 0) {
                [[UserManager standerDefult]playMusicWithMusicArray:_musicArr withCurrentIndex:0 withMusicPlayType:musicPlayType];
            }
        }
            break;
        case 1:
        {
            //批量
            self.isCompiling = !self.isCompiling;
            if (self.isCompiling) {
                //弹出批量框
                _tableView.height = self.view.height-_compileView.height;
                _compileView.top = _tableView.bottom;
                _compileView.hidden = NO;
            } else {
                //隐藏
                _tableView.height = self.view.height;
                _compileView.top = _tableView.bottom;
                _compileView.hidden = YES;
                self.isAllSelcting = NO; //不全选
                [_selectMusicArr removeAllObjects]; //删除所有选中的歌曲
                
                [[NSUserDefaults standardUserDefaults]setObject:@[] forKey:@"SELECT_MUSIC_FEN_ALL"];
                [[NSUserDefaults standardUserDefaults]synchronize];
            }
            //返回按钮改变
            [self onChangeBackButton:self.isCompiling];
            
            [_tableView reloadData];
        }
            break;
        case 2:
        {
            //更多
            //1.批量还原
            if (self.isCompiling) {
                UIButton *bt = (UIButton *)[self.view viewWithTag:1001];
                [self onTapForMusicAction:bt];
            }
            //2,显示
            ShowPlayerType playMusicType = ShowPlayerType_Moer;
            if (bgNoView.isHidden == NO && _type == MusicClassType_Custom) {
                //显示就 重命名和添加歌曲
                playMusicType = ShowPlayerType_AddNewMusic;
            }
            SharePLayerView *show = [[SharePLayerView alloc]initWithFrame:CGRectZero withType:(self.type == MusicClassType_Custom?ShowPlayerType_AddNewMusic:playMusicType)];
            show.delegate = self;
            show.orientation = self.orientation;
            [show onShowInWindow];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - 改变返回按钮样式
- (void)onChangeBackButton:(BOOL) compileStatus {
    if (compileStatus) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 60, 30);
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:14.]];
        [btn setTitle:@"全选" forState:UIControlStateNormal];
        [btn setTitle:@"全选" forState:UIControlStateHighlighted];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 25)];
        [btn addTarget:self action:@selector(onSelectTapAllMusicAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [self setLeftBarItem:btn];
        [self setRightBarItems:nil];
    } else {
        [self setBackItem];
        
        [self setRightPlayerItem];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 批量操作 取消、删除、收藏
- (void)onSelectItemForCancel:(MBSpaceCollectionCompileView *)view
{
    UIButton *bt = (UIButton *)[self.view viewWithTag:1001];
    [self onTapForMusicAction:bt];
}
//删除
- (void)onSelectItemForDelete:(MBSpaceCollectionCompileView *)view
{
    if (_selectMusicArr.count > 0) {
        NSMutableArray *newArr = [[NSMutableArray alloc]initWithArray:_selectMusicArr];
        UserModel *model = [UserManager standerDefult].userModel;
        if (!model) {
            MBLoginController *registerLastVC = [[MBLoginController alloc] init];
            registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
            [self.navigationController pushViewController:registerLastVC animated:YES];
            return;
        }
        
        NSMutableArray *idArr = [[NSMutableArray alloc]initWithCapacity:newArr.count];
        NSMutableArray *typeArr = [[NSMutableArray alloc]initWithCapacity:newArr.count];
        for (NSDictionary *dic in newArr) {
            
            NSString *proId = @"1";
            if ([dic.allKeys containsObject:@"ShowTitle"]) {
                proId = @"2";
            }
            
            [idArr addObject:[dic objectForKey:@"ID"]];
            [typeArr addObject:proId];
        }
        
        NSData *date = [NSJSONSerialization dataWithJSONObject:idArr options:NSJSONWritingPrettyPrinted error:nil];
        NSString *idString = [[NSString alloc]initWithData:date encoding:NSUTF8StringEncoding];
        NSData *date2 = [NSJSONSerialization dataWithJSONObject:typeArr options:NSJSONWritingPrettyPrinted error:nil];
        NSString *typeString = [[NSString alloc]initWithData:date2 encoding:NSUTF8StringEncoding];
        
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:SPACE_MOVEOUT_URL_PATH,model.UserID,idString,typeString,[_dataDic objectForKey:@"CateID"]] view:nil success:^(NSDictionary * json) {
            [MBProgressHUD hideHUDForView:_tableView animated:YES];
            if ([json[@"ret_code"] integerValue]==0) {
                
                for (NSDictionary *dic in newArr) {
                    FMManageObject *manager = [FMManageObject standerDefault];
                    //UI
                    NSUInteger index = [_musicArr indexOfObject:dic];
                    [_musicArr removeObject:dic];
                    [_tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                    if (_musicArr.count == 0) {
                        //已下载歌曲删除完
                        UIButton *bt = (UIButton *)[self.view viewWithTag:1001];
                        [self onTapForMusicAction:bt];
                        
                        _tableView.hidden = YES;
                        bgNoView.hidden = NO;
                        //                        _topView.hidden = bgNoView.isHidden;
                        [self onSetRightNavBar:_tableView.isHidden];
                        _showLb.hidden = NO;
                    }
                    
                    //数据库数据
                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    if ([dic.allKeys containsObject:@"AudioName"]) {
                        NSArray *arr = [manager SelectTableWithFileID:[dic objectForKey:@"ID"]];
                        if (arr.count > 0) {
                            [manager deleteCunstomFileID:[dic objectForKey:@"ID"]];
                        }
                        NSString *audioName = [NSString stringWithFormat:@"%@",[dic objectForKey:@"AudioName"]];
                        if ([[audioName componentsSeparatedByString:@"."]count] != 2) {
                            audioName = [NSString stringWithFormat:@"%@.mp3",audioName];
                        }
                        if ([fileManager fileExistsAtPath:[MusicCachesDirectory stringByAppendingPathComponent:audioName]]) {
                            [fileManager removeItemAtPath:[MusicCachesDirectory stringByAppendingPathComponent:audioName] error:NULL];
                        }
                        
                        
                        
                        NSArray *Marr = [[FMManageObject standerDefault]SelectTableWithFileID:[NSString stringWithFormat:@"%@",[dic objectForKey:@"fileID"]]];
                        if (Marr.count > 0) {
                            [[FMManageObject standerDefault]deleteCunstomFileID:[NSString stringWithFormat:@"%@",[dic objectForKey:@"fileID"]]];
                        }
                    }
                    else if ([dic.allKeys containsObject:@"ShowTitle"]) {
                        NSArray *arr = [manager SelectTableByLocalParentChildShowWithUserId:[NSString stringWithFormat:@"%@",[dic objectForKey:@"UserID"]] withMusicId:[NSString stringWithFormat:@"%@",[dic objectForKey:@"ID"]]];
                        if (arr.count > 0) {
                            NSDictionary *ss = [arr firstObject];
                            [manager deleteByLocalParentChildShowFilID:[ss objectForKey:@"id"]];
                        }
                        

                        if ([fileManager fileExistsAtPath:[MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"qzx_%@.mp3",[dic objectForKey:@"ShowTitle"]]]]) {
                            [fileManager removeItemAtPath:[MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"qzx_%@.mp3",[dic objectForKey:@"ShowTitle"]]] error:NULL];
                        }

                    }
                    
                }
                
                NSArray *musicArr = [[FMManageObject standerDefault]onSelectCustomMusicFileCount];
                [[UserManager standerDefult].downedMusicArr removeAllObjects];
                if (musicArr.count > 0) {
                    [[UserManager standerDefult].downedMusicArr addObjectsFromArray:musicArr];
                }
                NSArray *downedMusicArr = [UserManager standerDefult].downedMusicArr;
                [_fileIDArr removeAllObjects];
                NSMutableArray *arr1 = [[NSMutableArray alloc]init];
                NSMutableArray *arr2 = [[NSMutableArray alloc]init];
                for (int i=0; i<downedMusicArr.count; i++) {
                    NSDictionary *dic = [downedMusicArr objectAtIndex:i];
                    NSString *fileID = [dic objectForKey:@"fileID"];
                    [arr1 addObject:fileID];
                }
                NSArray *downedQZXMusicArr = [[FMManageObject standerDefault]onSelectLocalParentChildShowCount];
                for (int i=0; i<downedQZXMusicArr.count; i++) {
                    NSDictionary *dic = [downedQZXMusicArr objectAtIndex:i];
                    NSString *fileID = [dic objectForKey:@"musicId"];
                    if (![arr2 containsObject:fileID]) {
                        [arr2 addObject:fileID];
                    }
                }
                [_fileIDArr addObject:arr1];
                [_fileIDArr addObject:arr2];
                [_tableView reloadData];
                
                [ErrorMessage showErrorMessage:json[@"message"] inView:_tableView];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:_tableView animated:YES];
        }];
    }
    
    [_selectMusicArr removeAllObjects];
    
    [_tableView reloadData];
    if (_musicArr.count == 0) {
        //已下载歌曲删除完
        UIButton *bt = (UIButton *)[self.view viewWithTag:1001];
        [self onTapForMusicAction:bt];
        
        _tableView.hidden = YES;
        bgNoView.hidden = NO;
        //                        _topView.hidden = bgNoView.isHidden;
        [self onSetRightNavBar:_tableView.isHidden];
        _showLb.hidden = NO;
    }
    
}
//取消收藏
- (void)onSelectItemForNoCollection:(MBSpaceCollectionCompileView *)view
{
    if (_selectMusicArr.count > 0) {
        UserModel *model = [UserManager standerDefult].userModel;
        NSMutableArray *newArr = [[NSMutableArray alloc]initWithArray:_selectMusicArr];
        NSMutableArray *idArr = [[NSMutableArray alloc]initWithCapacity:newArr.count];
         NSMutableArray *typeArr = [[NSMutableArray alloc]initWithCapacity:newArr.count];
        
        for (NSDictionary *dic in newArr) {
            NSString *proId = @"1";
            NSString *idStr = [dic objectForKey:@"ID"];
            if ([dic.allKeys containsObject:@"ShowTitle"]) {
                proId = @"3";
                if (![[UserManager standerDefult].collectionShowArr containsObject:idStr]) {
                    continue;
                };
            } else {
                if (![[UserManager standerDefult].collectionMusicArr containsObject:idStr]) {
                    continue;
                };
            }
            
            [idArr addObject:idStr];
            [typeArr addObject:proId];
        }
        
        NSData *date = [NSJSONSerialization dataWithJSONObject:idArr options:NSJSONWritingPrettyPrinted error:nil];
        NSString *idString = [[NSString alloc]initWithData:date encoding:NSUTF8StringEncoding];
        NSData *date2 = [NSJSONSerialization dataWithJSONObject:typeArr options:NSJSONWritingPrettyPrinted error:nil];
        NSString *typeString = [[NSString alloc]initWithData:date2 encoding:NSUTF8StringEncoding];
        
        NSString*url=[NSString stringWithFormat:FAMILYSHOW_COLLECTION_CANCEL_URL_PATH,model.UserID,idString,typeString];
        [MBProgressHUD showHUDAddedTo:_tableView animated:YES];
        [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:_tableView animated:YES];
            if ([json[@"ret_code"] intValue] == 0) {
                for (NSDictionary *dic in newArr) {
                     NSString *idStr = [dic objectForKey:@"ID"];
                    if ([dic.allKeys containsObject:@"ShowTitle"]) {
                        if (![[UserManager standerDefult].collectionShowArr containsObject:idStr]) {
                            [[UserManager standerDefult].collectionShowArr removeObject:idStr];
                        }
                    } else {
                        if ([[UserManager standerDefult].collectionMusicArr containsObject:idStr]) {
                            [[UserManager standerDefult].collectionMusicArr removeObject:idStr];
                        }
                    }
                   
                }
                [ErrorMessage showErrorMessage:json[@"message"] inView:_tableView];
            }
            
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:_tableView animated:YES];
        }];
    }
    
    [_selectMusicArr removeAllObjects];
    if (_musicArr.count == 0) {
        //已下载歌曲删除完
        UIButton *bt = (UIButton *)[self.view viewWithTag:1001];
        [self onTapForMusicAction:bt];
    }

}

#pragma mark - 勾选一首歌曲
- (void)onSelectItemForGouXuanWithValue:(id)value WithSelect:(BOOL)isSelect WithView:(MBSpaceCollectionMusicCell *)view
{
    //数据保存
    NSLog(@"数据是否需要保存:%d",isSelect);
    if (isSelect) {
        //保存
        [_selectMusicArr addObject:value];
    } else {
        //删除
        if ([_selectMusicArr containsObject:value]) {
            [_selectMusicArr removeObject:value];
        }
    }
    
    //删除、收藏是否可选中
    [_compileView onUpdateDataForDelegateAndCollection:(_selectMusicArr.count > 0 ? YES : NO)];
    
    if (_selectMusicArr.count != _musicArr.count) {
        //不是全选 所有显示全选
        [self onChangeBackButton:YES];
    }
}


#pragma mark - 全选
- (void)onSelectAllMusicAction:(BOOL)isAllSelect
{
    self.isAllSelcting = isAllSelect;
    
    //测试
    [_selectMusicArr removeAllObjects];
    if (isAllSelect) {
        [_selectMusicArr addObjectsFromArray:_musicArr];
    }
    
    //删除、收藏是否可选中
    [_compileView onUpdateDataForDelegateAndCollection:(_selectMusicArr.count > 0 ? YES : NO)];
    
    [_tableView reloadData];}

//全选
- (void)onSelectTapAllMusicAction:(UIButton *)bt
{
    bt.selected = !bt.selected;
    if (bt.selected) {
        [bt setTitle:@"全不选" forState:UIControlStateNormal];
        [bt setTitle:@"全不选" forState:UIControlStateHighlighted];
        [bt setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
    } else {
        [bt setTitle:@"全选" forState:UIControlStateNormal];
        [bt setTitle:@"全选" forState:UIControlStateHighlighted];
        [bt setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 25)];
    }
    [self onSelectAllMusicAction:bt.selected];
}

#pragma mark - 更多操作 添加歌曲、播放、分享、取消收藏、下载
//添加歌曲
- (void)onSelctItemForMoreAddMusic:(SharePLayerView *)view
{
    MBSpaceAddMusicViewController *addMusic = [[MBSpaceAddMusicViewController alloc]init];
    addMusic.type = MBSpaceAddMusicType_SetAlbum;
    addMusic.dataDic = _dataDic;
    [self.navigationController pushViewController:addMusic animated:YES];
}

//每个歌曲更多操作
- (void)onSelectItemForMoewWithValue:(id)value withView:(MBSpaceCollectionMusicCell *)view
{
    if (value) {
        [_selectCurrentMusicDic removeAllObjects];
        [_selectCurrentMusicDic addEntriesFromDictionary:value];
        
        //判断下载
        NSString *idStr = [NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"ID"]];
        NSArray *mtArr;
        if ([[_selectCurrentMusicDic objectForKey:@"ProType"]intValue] == 1) {
            //音频
            mtArr = [_fileIDArr objectAtIndex:0];
        } else {
            mtArr = [_fileIDArr objectAtIndex:1];
        }
        BOOL isDown = NO;
        if ([mtArr containsObject:idStr]) {
            isDown = YES;
        }
        
        //判断收藏
        NSArray *collectionArr = [UserManager standerDefult].collectionMusicArr;
        BOOL isCollection = NO;
        if ([collectionArr containsObject:[NSNumber numberWithInt:[idStr intValue]]] || [collectionArr containsObject:idStr]) {
            isCollection = YES;
        }
        
        ShowPlayerType type = ShowPlayerType_MusicMoew;
        if (isCollection) {
            //已收藏
            if (isDown) {
                //已下载
                type = ShowPlayerType_MusicMoew;
            } else {
                type = ShowPlayerType_CancelCollectionDowned;
            }
        } else {
            //未收藏
            if (isDown) {
                //已下载
                type = ShowPlayerType_CollectionDowned;
            } else {
                type = ShowPlayerType_StroyAllList;
            }
        }
        
        SharePLayerView *show = [[SharePLayerView alloc]initWithFrame:CGRectZero withType:type];
        show.delegate = self;
        show.orientation = self.orientation;
        [show onShowInWindow];
    }
}

//播放
- (void)onSelctItemForMorePlayMusic:(SharePLayerView *)view
{
    if ([[_selectCurrentMusicDic objectForKey:@"AudioStatus"] intValue] == 0) {
//        return;
    }
    
    //音频
    NSMutableArray *newMusicArr = [[NSMutableArray alloc]init];
    if ([_selectCurrentMusicDic.allKeys containsObject:@"AudioName"]) {
        //收集歌曲了
        for (NSDictionary *dictionary in _musicArr) {
            if ([dictionary.allKeys containsObject:@"AudioName"]) {
                [newMusicArr addObject:dictionary];
            }
        }
        
        NSInteger indexPD = 0;
        if ([newMusicArr containsObject:_selectCurrentMusicDic]) {
            indexPD = [newMusicArr indexOfObject:_selectCurrentMusicDic];
        }
        
        [[UserManager standerDefult]playMusicWithMusicArray:newMusicArr withCurrentIndex:indexPD withMusicPlayType:musicPlayType];
    }
    else if ([_selectCurrentMusicDic.allKeys containsObject:@"ShowTitle"]) {
        //收集歌曲了
        for (NSDictionary *dictionary in _musicArr) {
            if ([dictionary.allKeys containsObject:@"ShowTitle"]) {
                [newMusicArr addObject:dictionary];
            }
        }
        
        NSInteger indexPD = 0;
        UserManager *manager = [UserManager standerDefult];
        if ([newMusicArr containsObject:_selectCurrentMusicDic]) {
            indexPD = [newMusicArr indexOfObject:_selectCurrentMusicDic];
        }
        
        NSString *idStr ;
        if (manager.audioPlayerType != AudioPLayerType_Qinzix) {
            //初次进入
            idStr = @"";
            manager.audioPlayerType = AudioPLayerType_Qinzix;
        } else {
            //2次进入
            NSInteger selectIndex = manager.selectMusicIndex;
            NSArray *arr = manager.musicArr;
            Music *dics = [arr objectAtIndex:selectIndex];
            idStr = [NSString stringWithFormat:@"%@",dics.ID];
        }
        [manager setSelectMusicIndex:indexPD];
        [manager.musicArr removeAllObjects];
        [manager.musicArr addObjectsFromArray:[manager onTurnArrayFormQingZiXiuArray:newMusicArr]];
        [manager.qinzixiuArr removeAllObjects];
        [manager.qinzixiuArr addObjectsFromArray:newMusicArr];
        
        MBDetailViewController *childShowVC = [[MBDetailViewController alloc] init];
        [childShowVC.dataAllArr addObjectsFromArray:newMusicArr];
        childShowVC.selectMusicID = idStr;
        [self.navigationController pushViewController:childShowVC animated:YES];

    }

}

//分享
- (void)onSelctItemForMoreShareMusic:(SharePLayerView *)view
{
    NSNumber *num = @1;
    NSString *audioName = [_selectCurrentMusicDic objectForKey:@"AudioName"];
    NSString *idStr = [_selectCurrentMusicDic objectForKey:@"ID"];
    NSString *url = [NSString stringWithFormat:SHARE_MUSIC_URL_PATH,idStr];
    if ([_selectCurrentMusicDic.allKeys containsObject:@"ShowTitle"]) {
        num = @3;
        audioName = [_selectCurrentMusicDic objectForKey:@"ShowTitle"];
        url = [NSString stringWithFormat:SHARE_SHOW_URL_PATH,idStr];
    }
    audioName = [[audioName componentsSeparatedByString:@"."]firstObject];
    [shareView setShareVC:self content:[NSString stringWithFormat:@"分享:%@",audioName] image:[UIImage imageNamed:@"logo_dl_29"] url:url];
    [shareView addAudioId:[NSString stringWithFormat:@"%@",idStr] withType:num];
    [shareView show];

}


//收藏
- (void)onSelctItemForMoreCollectionMusic:(SharePLayerView *)view;
{
    UserModel *model = [UserManager standerDefult].userModel;
    NSString*url=[NSString stringWithFormat:FAMILYSHOW_COLLECTION_ADD_URL_PATH,model.UserID,[_selectCurrentMusicDic objectForKey:@"ID"],@1];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(id json) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([json[@"ret_code"] intValue] == 0) {
            if (![[UserManager standerDefult].collectionMusicArr containsObject:[_selectCurrentMusicDic objectForKey:@"ID"]]) {
                [[UserManager standerDefult].collectionMusicArr addObject:[_selectCurrentMusicDic objectForKey:@"ID"]];
            }
        }
        [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];

}

//取消收藏
- (void)onSelctItemForMoreCancelMusicCollection:(SharePLayerView *)view
{
    UserModel *model = [UserManager standerDefult].userModel;
    NSString*url=[NSString stringWithFormat:FAMILYSHOW_COLLECTION_CANCEL_URL_PATH,model.UserID,[_selectCurrentMusicDic objectForKey:@"ID"],@1];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(id json) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if ([json[@"ret_code"] intValue] == 0) {
            if ([[UserManager standerDefult].collectionMusicArr containsObject:[_selectCurrentMusicDic objectForKey:@"ID"]]) {
                [[UserManager standerDefult].collectionMusicArr removeObject:[_selectCurrentMusicDic objectForKey:@"ID"]];
            }
        }

        
       [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];

}

//下载
- (void)onSelctItemForMoreDownMusic:(SharePLayerView *)view
{
    NSLog(@"取消收藏音乐");
    if (_selectCurrentMusicDic.allKeys.count > 0 && (view.type == ShowPlayerType_CancelCollectionDowned || view.type == ShowPlayerType_StroyAllList)) {
        if ([_selectCurrentMusicDic.allKeys containsObject:@"AudioName"]) {
            [[UserManager standerDefult]downLoadMusic:_selectCurrentMusicDic withRequestArr:[_fileIDArr objectAtIndex:0]];
        }
        else if ([_selectCurrentMusicDic.allKeys containsObject:@"ShowTitle"]) {
            
            NSDate *date = [NSDate date];
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *dateString = [formatter stringFromDate:date];
            
            [[DownManager staredInstance]downloadWithUrl:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,[_selectCurrentMusicDic objectForKey:@"FilePath"]]
                                           withMusicName:[NSString stringWithFormat:@"%@.mp3",[_selectCurrentMusicDic objectForKey:@"ShowTitle"]]
                                              withUserID:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"UserID"]]
                                             withMusicID:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"ID"]]
                                             withContent:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"Sentiment"]]
                                           withMusicType:[NSString stringWithFormat:@"%@",[[_selectCurrentMusicDic objectForKey:@"ShowType"] intValue]==1?@"5":@"6"]
                                              withPicUrl:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,[_selectCurrentMusicDic objectForKey:@"CoverPath"]]
                                                withDate:dateString
                                             withUserPic:@""
                                            withUserNick:@""
                                                withSize:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"Capacity"]]
                                            withProgress:^(CGFloat progress, NSString *speed, NSString *remainingTime, NSString *writtenSize, NSString *totalSize) {
                                                
                                            } withStats:^(DownMusicState stats) {
                                                
                                            }];
        }
        [ErrorMessage showErrorMessage:@"开始下载" inView:self.view];
    }
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _musicArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //歌曲
    static NSString *cellID = @"Collection_Music_Cell";
    MBSpaceCollectionMusicCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[MBSpaceCollectionMusicCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.delegate = self;
    }
    //是否隐藏更多按钮
    cell.isHideMoewBt = NO;
    [cell onCompileCellForLayout:self.isCompiling WithAllSelct:self.isAllSelcting];
    if (_musicArr.count > indexPath.row) {
        NSDictionary *dic = [_musicArr objectAtIndex:indexPath.row];
        cell.downedDic = dic;
        
        NSString *string = [NSString stringWithFormat:@"%@",[dic objectForKey:@"ID"]];
        NSArray *mtArr;
        if ([[dic objectForKey:@"ProType"]intValue] == 1) {
            //音频
            mtArr = [_fileIDArr objectAtIndex:0];
        } else {
            mtArr = [_fileIDArr objectAtIndex:1];
        }
        
        BOOL isShowDowned = NO;
        for (NSString *idStr in mtArr) {
            if ([string isEqualToString:idStr]) {
                isShowDowned = YES;
            }
        }
        cell.isShowDowned = isShowDowned;
    }
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100*PERCEN;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //编译状态不能点击
    if (!self.isCompiling) {//播放只能播放一系列歌曲 如：音频都播放音频 中间有亲子秀就跳过
        NSDictionary *dic = [_musicArr objectAtIndex:indexPath.row];
        UserManager *manager = [UserManager standerDefult];
        NSMutableArray *nArr = [[NSMutableArray alloc]initWithObjects:dic, nil];
        //存储一系列的歌曲列表
        NSMutableArray *newMusicArr = [[NSMutableArray alloc]init];
        //音频
        if ([dic.allKeys containsObject:@"AudioName"]) {
            
            //收集歌曲了
            for (NSDictionary *dictionary in _musicArr) {
                 if ([dictionary.allKeys containsObject:@"AudioName"]) {
                     [newMusicArr addObject:dictionary];
                 }
            }
            
            NSInteger indexPD = 0;
            if ([newMusicArr containsObject:dic]) {
                indexPD = [newMusicArr indexOfObject:dic];
            }
            
            if ([UserManager standerDefult].musicPlayType != musicPlayType) {
                //第一次
                [[UserManager standerDefult]playMusicWithMusicArray:newMusicArr withCurrentIndex:indexPD withMusicPlayType:musicPlayType];
            }
            else if ([UserManager standerDefult].selectMusicIndex != indexPD) {
                //当前页面播放
                [[UserManager standerDefult]playMusicWithMusicArray:newMusicArr withCurrentIndex:indexPD withMusicPlayType:musicPlayType];
            } else {
                //2次点击进入播放页面
                if ([UserManager standerDefult].musicArr.count > 0) {
                    //歌曲列表没歌曲 无需进入
                    UserManager *manager = [UserManager standerDefult];
                    [manager setSelectMusicIndex:indexPD];
                    if (manager.audioPlayerType != AudioPLayerType_YinPin) {
                        [manager setIsPlaying:NO];
                        [manager setAudioPlayerType:AudioPLayerType_YinPin];
                    } else {
                        [manager setIsPlaying:YES];
                    }
                    
                    if (ISIPAD) {
                        MBSongDetailForIpadController*song=[[MBSongDetailForIpadController alloc]init];
                        [self.navigationController pushViewController:song animated:YES];
                        return;
                    }
                    
                    MBSongDetailController *song = [[MBSongDetailController alloc]init];
                    [self.navigationController pushViewController:song animated:YES];
                }

            }

        }
        //亲子秀
        else if ([dic.allKeys containsObject:@"ShowTitle"]) {
            
            //收集歌曲了
            for (NSDictionary *dictionary in _musicArr) {
                if ([dictionary.allKeys containsObject:@"ShowTitle"]) {
                    [newMusicArr addObject:dictionary];
                }
            }
            
            NSInteger indexPD = 0;
            if ([newMusicArr containsObject:dic]) {
                indexPD = [newMusicArr indexOfObject:dic];
            }
            
            NSString *idStr ;
            if (manager.audioPlayerType != AudioPLayerType_Qinzix) {
                //初次进入
                idStr = @"";
                manager.audioPlayerType = AudioPLayerType_Qinzix;
            } else {
                //2次进入
                NSInteger selectIndex = manager.selectMusicIndex;
                NSArray *arr = manager.musicArr;
                Music *dics = [arr objectAtIndex:selectIndex];
                idStr = [NSString stringWithFormat:@"%@",dics.ID];
            }
            [manager setSelectMusicIndex:indexPD];
            [manager.musicArr removeAllObjects];
            [manager.musicArr addObjectsFromArray:[manager onTurnArrayFormQingZiXiuArray:newMusicArr]];
            [manager.qinzixiuArr removeAllObjects];
            [manager.qinzixiuArr addObjectsFromArray:newMusicArr];
            
            MBDetailViewController *childShowVC = [[MBDetailViewController alloc] init];
            [childShowVC.dataAllArr addObjectsFromArray:newMusicArr];
            childShowVC.selectMusicID = idStr;
            [self.navigationController pushViewController:childShowVC animated:YES];
            
        }
        
        
    }
    else {
        //编辑状态就选中勾选
        MBSpaceCollectionMusicCell *cell = (MBSpaceCollectionMusicCell *)[tableView cellForRowAtIndexPath:indexPath];
        if ([cell isKindOfClass:[MBSpaceCollectionMusicCell class]]) {
            [cell onGouXuanToSelectAction:cell.selectBt];
        }
    }
}

#pragma mark - 更多操作-重命名、添加歌曲
- (void)onSelectItemForMore
{
    SharePLayerView *show = [[SharePLayerView alloc]initWithFrame:CGRectZero withType:ShowPlayerType_AddNewMusic];
    show.delegate = self;
    show.orientation = self.orientation;
    [show onShowInWindow];
}
//重命名
- (void)onSelctItemForMoreChangeNewMusicName:(SharePLayerView *)view
{
    if (!_dataDic) return;
    
    NSString *cateId = [_dataDic objectForKey:@"CateID"];
    if (cateId) {
        MBSpaceChangeAlbumNameViewController *changeName = [[MBSpaceChangeAlbumNameViewController alloc]init];
        changeName.dataDic = _dataDic;
        [self.navigationController pushViewController:changeName animated:YES];
    }
}

@end
